﻿var action = 'Init';
var MaxRecords = 5;
var MaxRecordsInOnePage = MaxRecords;
var OldScreenWidth = 0;

$(document).ready(function ()
{
    InvlidSessionRedirection();
    reloop();
    summary();
    if (OldScreenWidth == 0)
    {
        OldScreenWidth = window.innerWidth;
    }

    $('#btnHome').click(function ()
    {
        summary();
    });
    $('#btnExpense').click(function ()
    {
        CurrentStep = 'AddExpense';
        $('#idTitle').html('Expense Details');
        Init();
        //show expenses
        Step(CurrentStep, action);
    });
    //Click toolbar to show income
    $('#btnIncome').click(function ()
    {
        CurrentStep = 'AddIncome';
        $('#idTitle').html('Income Details');
        Init();

        //show incomes
        Step(CurrentStep, action);
    });
    $('#btnCategory').click(function ()
    {
        CurrentStep = 'AddCategory';
        $('#idTitle').html('Category Details');
        Init();
        //show categories
        Step(CurrentStep, action);
    });

    $('#btnSetting').click(function ()
    {
        var bln = window.confirm("Please confirm?");
        if (bln)
        {
            $.ajax({
                type: "POST",
                url: "Login/Login.ashx",
                data: "mode=Logout",
                async: false,
                success: function (data)
                {
                    self.location = "Login/Login.htm"
                }
            });
        }
    });

    //Add something new
    $('#idAdd').click(function ()
    {
        action = 'Add';
        $('#idWaiting').show();
        Step(CurrentStep, action);
    });

    //delete a model
    $('#idDel').click(function ()
    {
        var record = GetAllSelected();
        if (record != '')
        {
            if (confirm('Confirmation Required!'))
            {
                $.ajax({
                    type: "POST",
                    url: "General.ashx",
                    data: "mode=DelRecords&type=" + CurrentStep + "&record=" + record,
                    async: false,
                    success: function (data)
                    {
                        CallBackAction(CurrentStep, 'Del');
                    }
                });
            }
        }
    });
});

function summary()
{
    CurrentStep = 'Home';
    $('#idTitle').show();
    $('#idTitle').html('Select a period:');
    Init();
    Step(CurrentStep, action);
    $('#idAdd').hide();
    $('#idWaiting').hide();
}

function InvlidSessionRedirection()
{
    $.ajax({
        type: "POST",
        url: "General.ashx",
        data: "mode=fetchSessionId",
        async: true,
        success: function (data)
        {
            if (data.length > 10)
            {
                self.location = "login/login.htm";
            }
        }
    });
}

//call back action
function CallBackAction(CurrentStep, action)
{
    switch (action)
    {
        case 'Del':
        case 'Add':
            switch (CurrentStep)
            {
                case 'AddExpense':
                    $('#btnExpense').click();
                    break;
                case 'AddIncome':
                    $('#btnIncome').click();
                    break;
                case 'AddCategory':
                    $('#btnCategory').click();
                    break;
            }
            break;
    }
}


function Init()
{
    $('#idContent').show();
    $('#idWaiting').show();
    $('#idDynamic').empty();
    $('#idDel').hide();
    $('#idEdit').hide();
    $('#idAdd').show();
    action = 'Init';
    $('#img2Top').hide(); 
}

//sub step
function Step(s, a)
{
    switch (s)
    {
        case "Home":
            switch (action)
            {
                case "Init":
                    Add("Home");
                    break;
            }
            break;
        case "AddExpense":
            switch (action)
            {
                case 'Add':
                    $('#idTitle').html('Add Expense');
                    Add("AddExpense");
                    break;
                case "Init": //issue a record
                    Add("GetIncomes");
                    break;
            }
            break;
        case "AddIncome":
            switch (action)
            {
                case 'Add':
                    $('#idTitle').html('Add Income');
                    Add("GetAddIncome");
                    break;
                case "Init":
                    Add("GetIncomes");
                    break;
            }
            break;
        case "AddCategory":
            switch (action)
            {
                case 'Add':
                    $('#idTitle').html('Add Category');
                    $('#idWaiting').hide();
                    Add("GetAddCategory");
                    break;
                case "Init":
                    Add("GetCategories");
                    break;
            }
            break;
        case "Logout":
            break;
    }
}

function Add(mode)
{
    var returnGUI = '';
    switch (mode)
    {
        case "AddExpense":
        case "GetAddIncome":
            returnGUI = 'component/Addincome.htm';
            break;
        case "GetAddCategory":
            returnGUI = 'component/AddCategory.htm';
            break;
        case "GetCategories":
            returnGUI = 'component/ShowCategories.htm';
            break;
        case "GetIncomes":
            returnGUI = 'component/ShowIncomes.htm';
            break;
        case "GetExpenses":
            returnGUI = 'component/ShowIncomes.htm';
            break;
        case "Home":
            returnGUI = 'component/summary.htm';
            break;
    }
    $('#idDynamic').empty();
    $('#idDynamic').load(returnGUI, function ()
    {
        switch (mode)
        {
            case "GetCategories":
            case "GetIncomes":
                $('#idWaiting').hide();
                $('#idTitle').hide();
                break;
        }
    });
}
//select & unselected models
function modelAction(model)
{
    if (model.hasClass('selected'))
    {
        model.removeClass('selected');
    }
    else
    {
        model.addClass('selected');
    }
    showDelete();
}

function modelActive(model, submodel)
{
    if (model.hasClass('active'))
    {
        model.removeClass('active');
        submodel.empty();  
    }
    else
    {
        model.addClass('active');
    }
}

//get all selected models
function GetAllSelected()
{
    var selectedIds = "";
    $(".model").each(function ()
    {
        if ($(this).hasClass('selected'))
        {
            selectedIds = selectedIds + $(this).attr('id') + '|';
        }
    });
    return selectedIds;
}

//if more than 1 tile was selected, show button delete
function showDelete()
{
    var record = GetAllSelected();
    if (record != '')
    {
        //show delete button
        $('#idDel').show();
    }
    else
    {
        $('#idDel').hide();
    }
}
//get type 1: income 2: expense
function GetRecordType(CurrentStep)
{
    var type = 0;
    switch (CurrentStep)
    {
        case 'AddIncome':
            type = 1;
            break;
        case 'AddExpense':
            type = 2;
            break;
    }
    return type;
}


//calculate the pages
function calculatePaging(lenOfData, id)
{
    shown = shown + lenOfData;
    left = total - shown;
    if (0 != left)
    {
        if (left > MaxRecords)
        {
            left = MaxRecords;
        }
    }
    
    if (0 == left)
    {
        id.show();
        id.html('Total: '+total + ' record(s)');
    }
    else
    {
        //$('#idShowMoreRecords').show();
        //$('#idShowMoreRecords').html('Show next ' + left + ' record(s)');
        id.show();
        id.html('Show next ' + left + '/'+total+' record(s).');
    }
}

function GenerateMoreRecords(result, id)
{
    total = result.total;
    for (var i = 0; i < result.data.length; i++)
    {
        var category = result.data[i].category;
        var key = result.data[i].key;
        var amount = result.data[i].amount;
        var notes = result.data[i].Notes;
        var date = result.data[i].Date;
        var cell = "<div  class='data'  id='" + key.toString() + "'><h4 style='color:Red;'>" + category + " : $" + amount + "</h4><h4>Date:" + date + "</h4> <h5>Notes:" + notes + "<h5></div>"
        $('.listview').append('<li class="model" id=' + key.toString() + ' style="border:1px solid black;">' + cell + '</li>');
    }
    $('.cWaiting').hide();
    calculatePaging(result.data.length, id);
}

function reloop()
{
    var newWidth = window.innerWidth;
    if (newWidth != OldScreenWidth)
    {
        OldScreenWidth = newWidth;
        //Can do something complicated
    }
    AjustGUI();
    setTimeout("reloop()", 2000);
}

function AjustGUI()
{
    var width = window.innerWidth;
    if (width <= 320)
    {
        $('#btnCategory').html('');
        $('#btnSetting').html('');
    }
    else
    {
        $('#btnCategory').html('Category');
        $('#btnSetting').html('Logout');
    }
}

$(window).bind("scroll", function ()
{
    $('#id2Top').show();
    $('#img2Top').fadeIn('slow');
});
function Go2Top()
{
    $('body,html').animate({ scrollTop: 0 }, 500, function ()
    {
        $('#img2Top').fadeOut('fast');
    });
}

function tf(str)
{
    return str.replace(/\`/g, '\'');
}